package com.zipking.cloud.springbootmybatis.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Maps;
import com.zipking.cloud.springbootmybatis.persistance.entity.MsgLog;
import com.zipking.cloud.springbootmybatis.persistance.mapper.MsgLogMapper;
import com.zipking.cloud.springbootmybatis.service.ExportService;
import com.zipking.cloud.springbootmybatis.util.excel.DemoData;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ExportServiceImpl  implements ExportService{
    @Autowired
    private MsgLogMapper msgLogMapper;
    @Autowired
    private ThreadPoolTaskExecutor queryBatchPool;
    @Override
    public void exportData(String param, HttpServletResponse response) {

// 创建线程池

        // 分批次查询数据
        int pageSize = 1000;
        int pageNum = 1;
        final boolean  hasNextPage =  true ;
        while (hasNextPage) {
            Map<@Nullable String, @Nullable Object> mapext = Maps.newHashMap();
            int finalPageNum = pageNum;
            queryBatchPool.submit(() -> {
                mapext.put("limit", pageSize);
                mapext.put("num", finalPageNum);
                List<MsgLog> dataList = msgLogMapper.selectListByWhere(mapext);
               /* if (CollectionUtils.isEmpty(dataList)) {
                    hasNextPage  = false;
                    break;
                }*/

                // 使用 EasyExcel 进行导出
                try (OutputStream out = response.getOutputStream()) {
                    // 导出数据
                    EasyExcel.write(out, DemoData.class).sheet("模板").doWrite(dataList);
                } catch (Exception e) {
                    // 异常处理
                }
            });

            pageNum++;
        }

        // 关闭线程池
        //executorService.shutdown();

    }
}
